package com.example.demo.controller;

import com.example.demo.Service.MessageService;

import com.example.demo.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @PostMapping("/send")
    public ResponseEntity<Message> sendMessage(@RequestParam Long senderId, @RequestParam Long receiverId, @RequestParam String content) {
        Message message = messageService.createMessage(senderId, receiverId, content);
        return ResponseEntity.ok(message);
    }

    @DeleteMapping("/delete/{messageId}")
    public ResponseEntity<String> deleteMessage(@PathVariable Long messageId) {
        messageService.deleteMessage(messageId);
        return ResponseEntity.ok("Message deleted successfully.");
    }

    @PutMapping("/update/{messageId}/read")
    public ResponseEntity<Message> updateMessageStatus(@PathVariable Long messageId, @RequestParam Boolean isRead) {
        Message message = messageService.updateMessageStatus(messageId, isRead);
        return ResponseEntity.ok(message);
    }

    @GetMapping("/list/{receiverId}")
    public ResponseEntity<List<Message>> listMessagesByReceiverId(@PathVariable Long receiverId) {
        List<Message> messages = messageService.listMessagesByReceiverId(receiverId);
        return ResponseEntity.ok(messages);
    }

    @GetMapping("/latest/{receiverId}")
    public ResponseEntity<Message> getLatestMessageByreceiverId(@PathVariable Long receiverId) {
        Message latestMessage = messageService.getLatestMessageByreceiverId(receiverId);
        if (latestMessage != null) {
            return ResponseEntity.ok(latestMessage);
        } else {
            // 返回一个空的消息对象，表示还没有发过消息
            return ResponseEntity.ok(new Message());
        }
    }

    @GetMapping("/list/{senderId}/{receiverId}")
    public ResponseEntity<List<Message>> listMessagesBySenderAndReceiverId(@PathVariable Long senderId, @PathVariable Long receiverId) {
        List<Message> messages = messageService.getConversationBetweenUsers(senderId, receiverId);
        return ResponseEntity.ok(messages);
    }
    // 更多的控制器方法...
}